package com.ayf.payment.game.api.utils;

import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class IPUtils {

    public static String getIp(HttpServletRequest request) {
        String ip = getSubIp(request);
        if (StringUtils.isBlank(ip)) {
            return "";
        }
        String tmpIps[] = StringUtils.split(ip, ",");
        if (tmpIps == null || tmpIps.length == 0) {
            return "";
        }
        String ipStr = tmpIps[tmpIps.length - 1];
        int ipIndex = ipStr.indexOf(":");
        if (StringUtils.isNotEmpty(ipStr) && ipIndex!=-1){
            ipStr=ipStr.substring(0,ipIndex);
        }
        return ipStr;
    }

    private static String getSubIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        LogPortal.info("从 X-Forwarded-For 获取IP信息:{}",ipAddress);
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("X-Real-IP");
            LogPortal.info("从 X-Real-IP 获取IP信息:{}",ipAddress);
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
            LogPortal.info("从 Proxy-Client-IP 获取IP信息:{}",ipAddress);
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
            LogPortal.info("从 WL-Proxy-Client-IP 获取IP信息:{}",ipAddress);
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress iNet = null;
                try {
                    iNet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = iNet.getHostAddress();
                LogPortal.info("从 网卡取本机配置的IP 获取IP信息:{}",ipAddress);
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) {
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                LogPortal.info("从 通过多个代理的情况截取 获取IP信息:{}",ipAddress);
            }
        }
        return ipAddress;
    }
}
